package cn.gov.ssxmzj.service;

import cn.gov.ssxmzj.entry.ManagerInfo;
import cn.gov.ssxmzj.entry.MsgInfo;
import cn.gov.ssxmzj.entry.PageNews;
import cn.gov.ssxmzj.entry.Result;
import cn.gov.ssxmzj.mapper.ManagerMapper;
import cn.gov.ssxmzj.mapper.MsgMapper;
import cn.gov.ssxmzj.utils.DateUtils;
import cn.gov.ssxmzj.utils.StaticUtils;
import cn.gov.ssxmzj.utils.Utils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MsgService {

    @Autowired
    private MsgMapper msgMapper;
    @Autowired
    private ManagerMapper managerMapper;

    /**
     * 暂时只有 3-举报 4-局长信箱
     * @param msgInfo
     * @param msgType
     * @return
     */
    public Result sendMsg(String msgInfo,String msgType){
        //消息ID
        String msgId =Utils.createMsgId();
        //创建时间
        String createTime = DateUtils.getDate();
        String msgReceiver = null;
        String msgSender = null;
        String msgContent = null;
        //举报类型
        if(!Utils.isEmpty(msgInfo)&&"3|4".contains(msgType)){
            Map addMsg = (Map) JSON.parse(msgInfo);
            //举报类型的发送者设置为举报人的姓名
            msgSender = Utils.checkNull(String.valueOf(addMsg.get("name")));
            String telephone = Utils.checkNull(String.valueOf(addMsg.get("telephone")));
            String address = Utils.checkNull(String.valueOf(addMsg.get("address")));
            String reportContent = Utils.checkNull(String.valueOf(addMsg.get("reportContent")));
            msgContent = telephone+"},{"+address+"},{"+reportContent;
        }
        if(Utils.isEmpty(Utils.checkNull(msgContent))){
            return new Result(Result.SERVICE_ERROR,"提交的具体内容不能为空","");
        }
        MsgInfo msg = new MsgInfo(msgId,msgContent,msgSender,msgReceiver,msgType,createTime,"0","1",null,null);
        msgMapper.sendMsg(msg);
        return new Result(Result.SUCCESS,"发送成功","");
    }

    /**
     * 获取未读消息总数
     * @param managerId
     * @return
     */
    public Result getMsgNum(String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.ERROR,"登录已超时，请重新登录","");
        }
        Map sqlMap = Utils.asMap("managerId",managerId,"validTag","1");
        List<ManagerInfo> managerInfo = managerMapper.getManagerInfoByName(sqlMap);
        if(Utils.isEmpty(managerInfo)){
            return new Result(Result.ERROR,"登录已超时，请重新登录","");
        }
        //获取管理员权限,只有超级管理员可以查看举报
        String managerLevel = managerInfo.get(0).getManager_level();
        sqlMap.putAll(Utils.asMap("managerLevel",managerLevel,"readTag","0"));
        List<Integer> msgNumList = msgMapper.getMsgNum(sqlMap);
        int msgNum = 0;
        if(!Utils.isEmpty(msgNumList)){
            for (int num : msgNumList){
                msgNum += num;
            }
        }
        return new Result(Result.SUCCESS,"查询成功",msgNum>99?"99+":String.valueOf(msgNum));
    }

    /**
     * 获取所有的消息
     * @param msgType
     * @param isRead
     * @param managerId
     * @param page
     * @param limit
     * @return
     */
    public Result getMsgInfo(String msgType,String isRead,String managerId,int page,int limit){
        //先校验管理员信息
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.ERROR,"登录已超时，请重新登录","");
        }
        Map sqlMap = Utils.asMap("managerId",managerId,"validTag","1");
        List<ManagerInfo> managerInfo = managerMapper.getManagerInfoByName(sqlMap);
        if(Utils.isEmpty(managerInfo)){
            return new Result(Result.ERROR,"登录已超时，请重新登录","");
        }
        //获取管理员权限,只有超级管理员可以查看局长信箱
        String managerLevel = managerInfo.get(0).getManager_level();
        //默认查询未读消息
        isRead = Utils.isEmpty(Utils.checkNull(isRead))?"0":isRead;
        msgType = "0".equals(msgType)||Utils.isEmpty(msgType)?null:msgType;
        sqlMap.putAll(Utils.asMap("managerLevel",managerLevel,"readTag",isRead,"msgType",msgType));
        List<Integer> msgNumList = msgMapper.getMsgNum(sqlMap);
        int count = 0;
        if(!Utils.isEmpty(msgNumList)){
            for (int num : msgNumList){
                count += num;
            }
        }
        if (count < 1){
            return new Result(Result.SERVICE_ERROR,"暂无消息","");
        }
        //处理页数
        page = 0 == page ? 0 : --page * limit;
        sqlMap.putAll(Utils.asMap("page",page,"limit",limit));
        //查询所有消息
        List<Map> msgInfoList = msgMapper.getAllMsgInfo(sqlMap);
        //转换参数
        for(Map msg : msgInfoList){
            if("3|4".contains(String.valueOf(msg.get("MSG_TYPE")))){
                String msgContent = String.valueOf(msg.get("MSG_CONTENT"));
                String[] content = msgContent.split("},\\{");
                if(!Utils.isEmpty(content)&&content.length==3){
                    msg.put("MSG_CONTENT", content[2]);
                }
            }
            msg.put("MSG_TYPE",Utils.changeMsgType(String.valueOf(msg.get("MSG_TYPE"))));
            msg.put("CREATE_TIME",DateUtils.changeDate(String.valueOf(msg.get("CREATE_TIME")),
                    "yyyyMMddHHmmss","yyyy-MM-dd HH:mm:ss"));
        }
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("data",msgInfoList)));
    }

    /**
     * 删除消息
     * @param msgId
     * @param managerId
     * @return
     */
    public Result deleteMsg(String msgId,String managerId){
        //校验工号信息
        Result checkManagerResult = checkManager(managerId);
        if(!Result.SUCCESS.equals(checkManagerResult.getStatus())){
            return checkManagerResult;
        }
        ManagerInfo managerInfo = (ManagerInfo) checkManagerResult.getData();
        //校验消息是否存在
        Map sqlMap = Utils.asMap("msgId",msgId);
        List<MsgInfo> msgInfoList = msgMapper.getMsgInfo(sqlMap);
        if(Utils.isEmpty(msgInfoList)){
            return new Result(Result.SERVICE_ERROR,"未获取带要操作的消息，请刷新页面重试","");
        }
        //校验工号是否有删除该消息的权限
        String managerLevel = managerInfo.getManager_level();
        String msgType = msgInfoList.get(0).getMsg_type();
        if("0".equals(msgInfoList.get(0).getRead_tag())){
            return new Result(Result.ERROR,"未读消息不允许删除","");
        }
        //超级管理员拥有一切权限
        if(!StaticUtils.SUPER_MANAGER_LEVEL.equals(managerLevel)){
            //局长信箱类型消息只有超级管理员可以处理
            if(StaticUtils.SECRET_MSG.equals(msgType)){
                return new Result(Result.ERROR,"对不起，您的工号暂无权限操作该类型消息","");
            }//普通工号无权操作举报类型信息
            else if(StaticUtils.REPORT_MSG.equals(msgType)&&StaticUtils.DEFAULT_MANAGER_LEVEL.equals(managerLevel)){
                return new Result(Result.ERROR,"对不起，您的工号暂无权限操作该类型消息","");
            }
        }
        //暂无公告类型消息,因此不允许删除
        if(StaticUtils.NOTICE_MSG.equals(msgType)){
            return new Result(Result.ERROR,"对不起，您的工号暂无权限操作该类型消息","");
        }
        //无法操作发送给别人的消息
        if(StaticUtils.CHAT_MSG.equals(msgType)&&!managerId.equals(msgInfoList.get(0).getMsg_receiver())){
            return new Result(Result.ERROR,"对不起，您的工号暂无权限操作该消息","");
        }
        int deleteNum = msgMapper.deleteMsg(Utils.asMap("msgId",msgId));
        if(deleteNum < 1){
            return new Result(Result.SERVICE_ERROR,"未获取带要删除的消息，请刷新重试","");
        }
        return new Result(Result.SUCCESS,"删除成功","");
    }

    /**
     * 获取单个信息
     * @param msgId
     * @param managerId
     * @return
     */
    public Result getOneMsgInfo(String msgId,String managerId){
        //校验工号信息
        Result checkManagerResult = checkManager(managerId);
        if(!Result.SUCCESS.equals(checkManagerResult.getStatus())){
            return checkManagerResult;
        }
        ManagerInfo managerInfo = (ManagerInfo) checkManagerResult.getData();
        //获取管理员权限,只有超级管理员可以查看局长信箱
        String managerLevel = managerInfo.getManager_level();
        Map sqlMap = Utils.asMap("msgId",msgId,"managerId",managerId,"managerLevel",managerLevel,"page",0,"limit",1);
        //查询所有消息
        List<Map> msgInfoList = msgMapper.getAllMsgInfo(sqlMap);
        if(Utils.isEmpty(msgInfoList)){
            return new Result(Result.SERVICE_ERROR,"未获取到要查看的信息，请刷新后重试","");
        }
        Map msg = msgInfoList.get(0);
        //转换参数
        if("3|4".contains(String.valueOf(msg.get("MSG_TYPE")))){
            String msgContent = String.valueOf(msg.get("MSG_CONTENT"));
            String[] content = msgContent.split("},\\{");
            if(!Utils.isEmpty(content)&&content.length==3){
                msg.put("TELEPHONE", content[0]);
                msg.put("ADDRESS", content[1]);
                msg.put("MSG_CONTENT", content[2]);
            }
        }
        msg.put("MSG_TYPE",Utils.changeMsgType(String.valueOf(msg.get("MSG_TYPE"))));
        msg.put("CREATE_TIME",DateUtils.changeDate(String.valueOf(msg.get("CREATE_TIME")),
                "yyyyMMddHHmmss","yyyy-MM-dd HH:mm:ss"));
        return new Result(Result.SUCCESS,"查询成功",msg);
    }

    /**
     * 阅读消息
     * @param msgId
     * @param managerId
     * @return
     */
    public Result readMsg(String msgId,String managerId){
        //校验工号信息
        Result checkManagerResult = checkManager(managerId);
        if(!Result.SUCCESS.equals(checkManagerResult.getStatus())){
            return checkManagerResult;
        }
        //设置消息为已读
        int readLine = msgMapper.readMsg(Utils.asMap("msgId",msgId,"readTag","1"));
        if(readLine < 1){
            return new Result(Result.SERVICE_ERROR,"阅读消息失败","");
        }
        return new Result(Result.SUCCESS,"阅读消息成功","");
    }


    /**
     * 校验工号
     * @param managerId
     * @return
     */
    protected Result checkManager(String managerId){
        //先校验管理员信息
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.ERROR,"登录已超时，请重新登录","");
        }
        Map sqlMap = Utils.asMap("managerId",managerId,"validTag","1");
        List<ManagerInfo> managerInfo = managerMapper.getManagerInfoByName(sqlMap);
        if(Utils.isEmpty(managerInfo)){
            return new Result(Result.ERROR,"登录已超时，请重新登录","");
        }
        return new Result(Result.SUCCESS,"校验成功",managerInfo.get(0));
    }

}
